package com.ssm.comm.eureka;

import com.netflix.loadbalancer.Server;
import com.ssm.comm.dto.EurekaServiceAddressDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class EurekaServiceAddressSelector implements ServiceAddressSelector{
    private static final Logger log = LoggerFactory.getLogger(EurekaServiceAddressSelector.class);

    /**
     * 根据轮询策略选择一个地址
     * @param clientName ribbon.properties配置文件中配置项的前缀名, 如myclient
     * @return null表示该服务当前没有可用地址
     */
    public EurekaServiceAddressDTO selectOne(String clientName) {
        Server  selected = selectServer(clientName) ;
        if (null == selected) {
            log.warn("服务{}没有可用地址", clientName);
            return null;
        }
        log.debug("服务{}选择结果:{}", clientName, selected);
        return EurekaServiceAddressDTO.builder().
                host(selected.getHost()).port(selected.getPort()).build();

    }

    /**
     * 选出该服务所有可用地址
     * @param clientName
     * @return
     */
    public   List<EurekaServiceAddressDTO> selectAvailableServers(String clientName) {
        List<Server> serverList = selectServers(clientName);
        if (Objects.isNull(serverList) || serverList.size() ==0 ) {
            log.warn("服务{}没有可用地址", clientName);
            return Collections.emptyList();
        }
        log.debug("服务{}所有选择结果:{}", clientName, serverList);
        return serverList.stream().map(t->EurekaServiceAddressDTO.builder()
                .host(t.getHost()).port(t.getPort()).build()).collect(Collectors.toList());
    }

}
